import { Response } from 'express';
import prisma from '../lib/prisma';
import { UserRole } from '../types/prisma-types';
import type { User } from '../types/prisma-types';
import { AuthenticatedRequest } from '../types/auth';
import { StatusCodes } from '../constants/statusCodes';
import { logger } from '../utils/logger';
import { ApiError } from '../utils/ApiError';

interface LoginRequest {
  email: string;
  password: string;
}

interface RegisterRequest {
  email: string;
  password: string;
  name: string;
  role: UserRole;
}

interface AuthResponse {
  token: string;
  user: Omit<User, 'password'>;
}

export const authController = {
  async login(req: AuthenticatedRequest<LoginRequest>, res: Response) {
    const { email, password } = req.body;

    const user = await prisma.user.findUnique({
      where: { email }
    });

    if (!user) {
      throw new ApiError(StatusCodes.UNAUTHORIZED, 'Invalid credentials');
    }

    // TODO: Implement proper password verification
    if (password !== user.password) {
      throw new ApiError(StatusCodes.UNAUTHORIZED, 'Invalid credentials');
    }

    // TODO: Implement proper token generation
    const token = 'dummy_token';

    const response: AuthResponse = {
      token,
      user: {
        id: user.id,
        email: user.email,
        name: user.name,
        role: user.role,
        createdAt: user.createdAt,
        updatedAt: user.updatedAt,
        isActive: user.isActive
      }
    };

    logger.info('User logged in', { userId: user.id });
    res.json(response);
  },

  async register(req: AuthenticatedRequest<RegisterRequest>, res: Response) {
    const { email, password, name, role } = req.body;

    const existingUser = await prisma.user.findUnique({
      where: { email }
    });

    if (existingUser) {
      throw new ApiError(StatusCodes.CONFLICT, 'Email already registered');
    }

    const user = await prisma.user.create({
      data: {
        email,
        password, // TODO: Implement proper password hashing
        name,
        role
      },
      select: {
        id: true,
        email: true,
        name: true,
        role: true,
        createdAt: true,
        updatedAt: true,
        isActive: true
      }
    });

    // TODO: Implement proper token generation
    const token = 'dummy_token';

    const response: AuthResponse = {
      token,
      user
    };

    logger.info('New user registered', { userId: user.id });
    res.status(StatusCodes.CREATED).json(response);
  },

  async logout(req: AuthenticatedRequest, res: Response) {
    // TODO: Implement proper token invalidation
    logger.info('User logged out', { userId: req.user?.id });
    res.status(StatusCodes.NO_CONTENT).send();
  },

  async verifyToken(req: AuthenticatedRequest, res: Response) {
    const user = await prisma.user.findUnique({
      where: { id: req.user?.id },
      select: {
        id: true,
        email: true,
        name: true,
        role: true,
        createdAt: true,
        updatedAt: true,
        isActive: true
      }
    });

    if (!user) {
      throw new ApiError(StatusCodes.UNAUTHORIZED, 'Invalid token');
    }

    logger.info('Token verified', { userId: user.id });
    res.json({ user });
  }
};
